package org.school.Interceptor;
import com.alibaba.fastjson.JSONObject;
import org.school.entity.message2;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;

//    @Autowired
//    private StringRedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从请求头里面获取token,因为每次都会在请求头里面携带token
        System.out.println(request.getRequestURI());
        String token = request.getHeader("token");
        System.out.println("进入拦截");
        if (StringUtils.isNotBlank(token)) {
            //根据head中的token，查询redis中是否有数据
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            String tokenType = opsForValue.get(token);
            // 如果能够获取到数据，说明token未过期
            if (StringUtils.isNotBlank(tokenType)) {
                //在这里，我们需要对时间进行重置
                redisTemplate.expire(token,80*10, TimeUnit.MINUTES);
                return true;
            }else {//暂时
                message2 m=new message2("invaild token ",0);
               String s= JSONObject.toJSONString(m);
                response.getWriter().println(s);
                response.setStatus(200);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=utf-8");
                return false;
            }
        }



        try {
            PrintWriter pw = response.getWriter();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

